package com.lzm.seckill.server.service;

import com.lzm.seckill.server.dto.MailDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

/**
 * Description:邮件服务
 *
 * @Author: Liuzemin
 * @Date: 2020/9/17 14:03
 */
@EnableAsync
@Service
public class MailService {
    private final static Logger log = LoggerFactory.getLogger(MailService.class);

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private Environment env;
    /**
     * 发送简单邮件
     */
    @Async
    public void sendSimpleMail(final MailDto mailDto){
        try{
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(env.getProperty("mail.send.from"));
            message.setTo(mailDto.getTos());
            message.setSubject(mailDto.getSubject());
            message.setText(mailDto.getContent());
            javaMailSender.send(message);
            log.info("发送简单邮件-发送成功!");
        }catch (Exception e){
            log.error("发送简单邮件-发生异常：", e.fillInStackTrace());
        }
    }

    /**
     * 发送HTML格式邮件
     */
    @Async
    public void sendHtmlMail(final MailDto mailDto){
        try{
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            mimeMessageHelper.setFrom(env.getProperty("mail.send.from"));
            mimeMessageHelper.setTo(mailDto.getTos());
            mimeMessageHelper.setSubject(mailDto.getSubject());
            mimeMessageHelper.setText(mailDto.getContent(), true);
            javaMailSender.send(mimeMessage);
            log.info("发送HTML格式邮件-发送成功!");
        }catch (Exception e){
            log.error("发送HTML格式邮件-发生异常：", e.fillInStackTrace());
        }
    }
}
